<template>
	<div class="component-audio">
		<div class="btn-wrap">
			<van-button
				@click.native="playing ? pause() : play()"
				:disabled="!loaded"
				:icon="!playing || paused ? 'play' : 'pause'"
				plain
				hairline
				type="default"
				round
			/>
			<van-loading class="fixed-loading" v-show="!loaded || !reLoaded" />

			<van-button
				@click.native="stop()"
				:disabled="!loaded"
				icon="stop"
				plain
				hairline
				type="default"
				round
			/>
			<!-- <van-button
                @click.native="reload()"
                :disabled="!loaded"
                icon="replay"
                plain
                hairline
                type="default"
                round
            />-->
		</div>

		<van-progress
			ref="progress"
			:percentage="percentage"
			style="margin-top: 15px; margin-bottom: 15px"
			@touchmove.native="touchmove"
			@touchend.native="touchend"
			@click.native="setPosition"
			:show-pivot="false"
			:disabled="!loaded"
		></van-progress>
		<p>{{ currentTime }} / {{ duration }}</p>
		<audio
			id="player"
			ref="player"
			v-on:ended="ended"
			v-on:canplay="canPlay"
			:src="file"
		></audio>
	</div>
</template>
<script>
// import { throttle } from "filters/throttle.js";
const formatTime = (second) => new Date(second * 1000).toISOString().substr(11, 8);
export default {
	name: "Audio",
	props: {
		file: {
			type: String,
			default: null,
		},
		autoPlay: {
			type: Boolean,
			default: false,
		},
		ended: {
			type: Function,
			default: () => {},
		},
		canPlay: {
			type: Function,
			default: () => {},
		},
		downloadable: {
			type: Boolean,
			default: false,
		},
	},
	computed: {
		duration: function () {
			return this.audio ? formatTime(this.totalDuration) : "";
		},
	},
	data() {
		return {
			firstPlay: true,
			isMuted: false,
			loaded: false,
			playing: false,
			paused: false,
			percentage: 0,
			currentTime: "00:00:00",
			audio: undefined,
			totalDuration: 0,
			reLoaded: true,
		};
	},
	methods: {
		touchmove(e) {
			if (this.firstPlay) {
				return;
			}
			const { width, left } = this.$refs.progress.$el.getBoundingClientRect();
			const x = e.changedTouches[0].clientX - left;
			this.percentage = (x / width) * 100;
			console.log(0);
		},
		touchend() {
			if (this.firstPlay) {
				return;
			}
			this.reLoaded = false;
			this.audio.currentTime = parseInt((this.audio.duration / 100) * this.percentage);
		},
		setPosition(e) {
			if (this.firstPlay) {
				return;
			}
			const { width } = this.$refs.progress.$el.getBoundingClientRect();
			this.percentage = (e.offsetX / width) * 100;
			this.audio.currentTime = parseInt((this.audio.duration / 100) * this.percentage);
			this.reLoaded = false;
		},

		stop() {
			this.audio.pause();
			this.paused = true;
			this.playing = false;
			this.audio.currentTime = 0;
		},
		play() {
			if (this.playing) return;
			this.audio.play().then(() => (this.playing = true));
			this.paused = false;
		},
		pause() {
			this.paused = !this.paused;
			this.paused ? this.audio.pause() : this.audio.play();
		},
		download() {
			this.audio.pause();
			window.open(this.file, "download");
		},
		mute() {
			this.isMuted = !this.isMuted;
			this.audio.muted = this.isMuted;
			this.volumeValue = this.isMuted ? 0 : 75;
		},
		// reload() {
		// 	this.audio.load();
		// 	this.percentage = 0;
		// },
		_handleLoaded: function () {
			if (this.audio.readyState >= 2) {
				if (this.audio.duration === Infinity) {
					// Fix duration for streamed audio source or blob based
					// https://stackoverflow.com/questions/38443084/how-can-i-add-predefined-length-to-audio-recorded-from-mediarecorder-in-chrome/39971175#39971175
					this.audio.currentTime = 1e101;
					this.audio.ontimeupdate = () => {
						this.audio.ontimeupdate = () => {};
						this.audio.currentTime = 0;
						this.totalDuration = parseInt(this.audio.duration);
						this.loaded = true;
					};
				} else {
					this.totalDuration = parseInt(this.audio.duration);
					this.loaded = true;
				}
				if (this.autoPlay) this.audio.play();
			} else {
				throw new Error("Failed to load sound file");
			}
		},
		_handlePlayingUI: function () {
			this.reLoaded = true;
			this.percentage = (this.audio.currentTime / this.audio.duration) * 100;
			this.currentTime = formatTime(this.audio.currentTime);
			this.playing = true;
		},
		_handlePlayPause: function (e) {
			if (e.type === "play" && this.firstPlay) {
				// in some situations, audio.currentTime is the end one on chrome
				this.audio.currentTime = 0;
				if (this.firstPlay) {
					this.firstPlay = false;
				}
			}
			if (e.type === "pause" && this.paused === false && this.playing === false) {
				this.currentTime = "00:00:00";
			}
		},
		_handleEnded() {
			this.paused = this.playing = false;
		},
		init: function () {
			this.audio.addEventListener("timeupdate", this._handlePlayingUI);
			this.audio.addEventListener("loadeddata", this._handleLoaded);
			this.audio.addEventListener("pause", this._handlePlayPause);
			this.audio.addEventListener("play", this._handlePlayPause);
			this.audio.addEventListener("ended", this._handleEnded);
		},
	},
	mounted() {
		this.audio = this.$refs.player;
		this.init();
	},
	beforeDestroy() {
		this.audio.removeEventListener("timeupdate", this._handlePlayingUI);
		this.audio.removeEventListener("loadeddata", this._handleLoaded);
		this.audio.removeEventListener("pause", this._handlePlayPause);
		this.audio.removeEventListener("play", this._handlePlayPause);
		this.audio.removeEventListener("ended", this._handleEnded);
	},
};
</script>
<style scoped lang="scss">
.component-audio {
	width: 80%;
	margin: 10px auto;

	padding: 24px;
	background-color: #f2f3f5;
	border-radius: 4px;
	box-shadow: 0 2px 2px #ebedf0;
	color: #333;
	text-align: center;
	.btn-wrap {
		display: flex;
		justify-content: space-around;
		position: relative;
	}
	.fixed-loading {
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
	}
	// .van-progress {
	//     background: #535355;
	//     .van-progress__portion {
	//         background: #b0b0b1;
	//     }
	// }
}
</style>
